<?php
/**
 * 用户导入
 * User: Administrator
 * Date: 2020/12/4
 * Time: 11:09
 */
namespace App\Jobs;

use App\Models\User;
use App\Models\UserImportErrorLog;
use App\Models\UserImportRecord;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Redis;
use Log;

class UserUpload implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * The number of times the job may be attempted.
     * 最大失次数
     * @var int
     */
    public $tries = 5;

    /**
     * The number of seconds the job can run before timing out.
     * 队列任务最大运行时长（秒）
     * @var int
     */
    public $timeout = 120;

    private $lot;

    /**
     * 插入数据数组
     */
    private $insertData = [];

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($lot)
    {
        $this->lot = $lot;
    }

    /**
     * Determine the time at which the job should timeout.
     *
     * @return \DateTime
     */
    public function retryUntil()
    {
        return now()->addSeconds(5);
    }
    /**
     * Execute the job.
     * \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['date'])
     * @return void
     */
    public function handle()
    {
        Log::info('导入名称--'.$this->lot);
        $item = DB::table('user_import_record')->where('lot', $this->lot)->first();
        Log::info('导入信息--'.json_encode($item));
        // 数据总数
        $count = Redis::llen($item->redis_title);
        Log::info("导入的数据量--".$count);
        // 导入的数据
        $excelData = Redis::LRANGE($item->redis_title,0,-1);
        //Log::info("导入的数据--".json_encode($excelData));
        $num = 0;
        if ($excelData) {
            foreach ($excelData as $key=>$item) {
                $num++;
                $data = json_decode($item,true);
                $res = $this->handleData($data);
                Log::info("处理的数据--{$key}---".json_encode($res));
                if (empty($res)) {
                    continue;
                }
                $insertData[] = $res;
                $keyArr[] = $key;
                if(is_int($num / 200)){
                    // 插入数据
                    $this->insertData($insertData);
                    $insertData = [];
                    unset($key);
                    $keyArr = [];
                }
            }
            if(!empty($insertData)){
                $this->insertData($insertData);
            }
            UserImportRecord::where('lot',$this->lot)->update(['status'=>3,'finish_time'=>Carbon::now()]);
        }
        // 如果没有数据，删除此队列job
        if ($count == $num) {
            // 加入错误日志
            $this->addError();
            $this->job->delete();
        }
    }

    /**
     * 处理数据
     * @param $excelData
     * @return mixed
     */
    public function handleData($excelData){
        $data = [
            'name'                  => trimall($excelData[0]),
            'mobile'                => trimall($excelData[1])
        ];
        // 查看是否添加
        $user = User::where('mobile',trimall($excelData[1]))->where('name',trimall($excelData[0]))->first();
        if (!$user) {
            $data['created_at'] = Carbon::now();
            return $data;
        }
        return [];
    }

    /**
     * 插入数据
     * @param $insertData
     * @return mixed
     */
    public function insertData($insertData){
        Log::info("添加的数据---".json_encode($insertData));
        User::insert($insertData);
        return true;
    }

    /**
     * 加入错误日志
     */
    public function addError(){
        $data = Redis::LRANGE($this->lot.'_err',0,-1);
        $insert = [];
        if (!empty($data)) {
            foreach ($data as $key=>$item) {
                $itemData = json_decode($item,true);
                $insert[] = [
                    'uuid'      => guid(),
                    'lot'       => $this->lot,
                    'excel_data'=> json_encode($itemData['excel_data']),
                    'msg'       => $itemData['msg'],
                    'created_at'=> Carbon::now()
                ];
            }
        }
        UserImportErrorLog::insert($insert);
        // 删除redis
        Redis::del($this->lot.'_err');
    }
}